package edu.cth.scrabbit.client.ctrl;

import java.util.ArrayList;
import java.util.List;

import edu.cth.scrabbit.client.core.ClientModel;
import edu.cth.scrabbit.client.view.panels.LetterTile;
import edu.cth.scrabbit.server.core.ServerModel;
import edu.cth.scrabbit.shared.GameLetter;

public class ClientController implements IClientController {
	private static IClientController ctrl;
	private GameLetter selectedGameboardTile = null;
	private GameLetter lastSelectedUserLetter = null;
	private List<GameLetter> placedLetters = new ArrayList<GameLetter>();
	private List<GameLetter> chosenTiles = new ArrayList<GameLetter>();

	private ClientController() {
		// empty private constructor
	}

	public static IClientController getInstance() {
		if (ctrl == null) {
			ctrl = new ClientController();
		}
		return ctrl;
	}

	@Override
	public void hostGame(String nickname) {
		// Start a server
		ServerModel.getInstance().startListening();
		// Join the server
		ClientModel.getInstance().joinGame("localhost", nickname, true);
	}

	@Override
	public void joinGame(String ip, String nickname) {
		ClientModel.getInstance().joinGame(ip, nickname, false);
	}

	@Override
	public void startGame() {
		ClientModel.getInstance().startGame();
	}

	@Override
	public void select(GameLetter letter) {
		if (selectedGameboardTile != null && !(placedLetters.contains(letter))) {
			placedLetters.add(letter);
			chosenTiles.add(selectedGameboardTile);

			int x = selectedGameboardTile.getXIndex();
			int y = selectedGameboardTile.getYIndex();
			letter.setPosition(x, y);
			ClientModel.getInstance().addTemporaryLetter(letter);

			lastSelectedUserLetter = letter;
			selectedGameboardTile = null;
		}
	}
	
	@Override
	public void selectGameBoardTile(GameLetter letter) {
		if (!(chosenTiles.contains(letter))) {
			selectedGameboardTile = letter;
		}
	}

	@Override
	public void pass() {
		clear();
		ClientModel.getInstance().pass();
	}

	@Override
	public void swap() {
		clear();
		ClientModel.getInstance().swap();
	}

	@Override
	public void play() {
		if (placedLetters.isEmpty()) {
			// No letters have been placed, do nothing.
			return;
		}

		// Set the position in the letters themselves:
		for (int i = 0; i < placedLetters.size(); i++) {
			GameLetter gl = placedLetters.get(i);
			GameLetter lt = chosenTiles.get(i);
			gl.setPosition(lt.getXIndex(), lt.getYIndex());
		}

		ClientModel.getInstance().play(placedLetters);

		placedLetters.clear();
		chosenTiles.clear();
		lastSelectedUserLetter = null;
		selectedGameboardTile = null;
	}

	@Override
	public void clear() {
		ClientModel.getInstance().clear();

		placedLetters.clear();
		chosenTiles.clear();
		lastSelectedUserLetter = null;
		selectedGameboardTile = null;
	}

}
